from odoo import fields, models, api, _
from odoo.exceptions import ValidationError


class WrappedInBox(models.Model):
    _name = 'sb.wrapped.in.box'
    _description = 'Wrapped in the box'
    _order = 'sequence'

    sequence = fields.Integer(string="Sequence")
    name = fields.Char(default='New', string='Name', store=True, compute='_compute_name')
    pd_id = fields.Many2one('sb.packing.delivery', string='Packing Delivery')
    pl_ids = fields.Many2many('sb.picking.list', string='Picking List')
    ttl_qty = fields.Integer(string='TTL QTY', compute='_compute_ttl_qty')
    n_weight = fields.Float(string='N.W.(Box/kg)')
    g_weight = fields.Float(string='G.W.(Box/kg)', compute='_compute_g_weight', store=True, readonly=False)

    @api.depends('n_weight')
    def _compute_g_weight(self):
        for rec in self:
            rec.g_weight = rec.n_weight + 0.5

    @api.onchange('pl_ids', 'pl_ids.qty')
    def _compute_ttl_qty(self):
        for rec in self:
            rec.ttl_qty = sum(rec.pl_ids.mapped('qty'))

    @api.depends('pd_id', 'sequence')
    def _compute_name(self):
        for rec in self:
            if rec.pd_id:
                rec.name = rec.pd_id.name + ' - ' + str(rec.sequence)
            else:
                rec.name = 'New'

    @api.model
    def create(self, vals):
        # 自动分配 sequence
        if vals.get('pd_id'):
            max_seq = self.search([('pd_id', '=', vals['pd_id'])], order='sequence desc', limit=1)
            vals['sequence'] = (max_seq.sequence + 1) if max_seq else 1

        record = super().create(vals)

        if len(record.pl_ids) < 2:
            raise ValidationError(_("Each mixed box must have at least two records.❌"))

        # 同步毛重净重
        record._sync_weight_to_pl_ids()

        return record

    def unlink(self):
        pd_id = self.mapped('pd_id')
        res = super().unlink()
        for pd in pd_id:
            records = self.search([('pd_id', '=', pd.id)], order='sequence')
            for index, record in enumerate(records, start=1):
                record.sequence = index
        return res

    def write(self, vals):
        for rec in self:
            if 'pd_id' in vals or 'sequence' not in vals:
                pd_id = vals.get('pd_id') or rec.pd_id.id
                if pd_id:
                    max_seq = self.search([('pd_id', '=', pd_id)], order='sequence desc', limit=1)
                    vals['sequence'] = (max_seq.sequence + 1) if max_seq else 1

        res = super().write(vals)
        for rec in self:
            if len(rec.pl_ids) < 2:
                raise ValidationError(_("Each mixed box must have at least two records.❌"))

            if 'n_weight' in vals or 'g_weight' in vals:
                rec._sync_weight_to_pl_ids()

        return res

    def _sync_weight_to_pl_ids(self):
        """将当前 box 的毛重/净重同步到其 pl_ids 上"""
        for rec in self:
            for pl in rec.pl_ids:
                pl.write({
                    'n_weight': rec.n_weight,
                    'g_weight': rec.g_weight,
                })
